import { deleteSettingDeletedepartmentId, postSettingAdddepartment, postSettingEditdepartmentId } from "@/api/siderBar/setting"
import { message, Modal } from "ant-design-vue"

interface FormState {
    name?: string
}
type TriggerAction = 'create' | 'update'
type EntryItem = {
    departmentId: number
    departmentName: string
}
export function useActionDep(fn?: IFn) {
    const triggerAction = ref<TriggerAction>('create')
    const entryItem = ref<INullable<EntryItem>>(null)
    const { state: showActionDep, on: openActionDep, off: closeActionDep } = useSwitch(false)
    const isUpdate = computed(() => triggerAction.value === 'update')
    const {
        formRef,
        formLoading,
        formState,
        rules,
        handleFormSubmit,
        resetFormState,
        clearValidate
    } = useFormState<FormState>({
        getInitialState() {
            return {}
        },
        rules: {
            name: [
                { required: true }
            ]
        }
    })
    useEffectScope(() => {
        watch(showActionDep, () => {
            if (showActionDep.value === false) {
                clearValidate()
                resetFormState()
            }
        })
    })
    function handleTriggerAction<Action extends TriggerAction>(action: Action, entry: Action extends 'update' ? EntryItem : null) {
        triggerAction.value = action
        entryItem.value = entry
        populate()
        openActionDep()
    }
    function populate() {
        const patch = entryItem.value
        if (patch && triggerAction.value === 'update') {
            if (patch.departmentName) {
                formState.value.name = patch.departmentName
            }
        }
    }
    function reset() {
        closeActionDep()
        triggerAction.value = 'create'
        entryItem.value = null
    }
    async function handleSubmit() {
        const update = isUpdate.value
        await handleFormSubmit(values => {
            return update ? postSettingEditdepartmentId(entryItem.value!.departmentId, values) : postSettingAdddepartment(values)
        })
        reset()
        message.success(update ? '编辑成功' : '添加成功')
        fn?.()
    }
    function deleteDep(depId: number) {
        Modal.confirm({
            title: '确认提示',
            content: '确认要删除吗？',
            onOk() {
                return deleteSettingDeletedepartmentId(depId).then(() => {
                    message.success('删除成功')
                    fn?.()
                })
            },
        })
    }
    return {
        showActionDep,
        formLoading,
        formState,
        formRef,
        rules,
        handleTriggerAction,
        handleSubmit,
        isUpdate,
        deleteDep
    }
}